package com.zhuojy.equity.mall.admin.service.quartz;

import com.zhuojy.equity.mall.admin.common.pojo.QuartzParam;
import com.zhuojy.equity.mall.admin.service.job.QuartzJob;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;

import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @description: TODO
 * @author chen
 * @date 2024/4/15 19:28
 * @version 1.0
 */
@Service
@Slf4j
public class QuartzServiceImpl {

    @Resource(name = "scheduler")
    private Scheduler scheduler;

    public Boolean addJob(QuartzParam param,String withIdentity) {

        String jobName = param.getJobName();
        String jobGroup = param.getJobGroup();
        String cron = param.getCron();
        String description = param.getDescription();
        JobDataMap jobDataMap = param.getJobDataMap();

        JobKey jobKey = new JobKey(jobName, jobGroup);
        boolean flag = true;

        try {

            if (scheduler.checkExists(jobKey)) {
                log.error("该任务名称及任务组已存在！");
                flag = false;
            }

            //创建作业调度JobDetail
            JobDetail jobDetail = JobBuilder.newJob(QuartzJob.class)
                    .withIdentity(jobKey)   //由jobName和jobGroup组成的唯一标识
                    .withDescription(description)   //说明
                    .usingJobData(jobDataMap)       //用到的参数
                    .build();

            //通过触发器名和cron 表达式创建 Trigger
            Trigger trigger = TriggerBuilder.newTrigger()
                    .withIdentity(withIdentity)       //触发器名称
                    .startNow()     //指定开始时间
                    .withSchedule(CronScheduleBuilder.cronSchedule(cron))    //cron表达式
                    .build();

            //开启定时器
            scheduler.scheduleJob(jobDetail, trigger);
            scheduler.start();

            log.info("添加成功！- " + jobKey);

        } catch (SchedulerException e) {
            flag = false;
            throw new RuntimeException(e);
        }
        return flag;
    }
}
